package com.yff.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yff.dao.IUserDao;
import com.yff.dao.impl.UserDaoImpl;
import com.yff.model.User;
import com.yff.utils.StringUtils;


@WebServlet("/user")
public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = -3704200856467333570L;
	
	private IUserDao userDao=new UserDaoImpl();

	private Object sql;

	private Object params;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");		
		PrintWriter out=response.getWriter();
		HttpSession session = request.getSession();
		
		String type=request.getParameter("type");
		
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		Boolean flag=false;
		
		int ret=0;
		
		if(type.equals("login")) {
			login(request, response, out, username, password);
		}else if(type.equals("reg")) {
			reg(request, response, username, password);
		}else if(type.equals("logout")) {
	    	session.removeAttribute("loginInfo");
	    	session.invalidate();
	    	response.sendRedirect(request.getContextPath()+"/index");
		}else if (type.equals("getAll")) {
			String p=request.getParameter("page");
			int page;
			try {
				page=Integer.valueOf(p);
			} catch (Exception e) {
				page=1;
			}
			int pageSize=3;
			int beginIndex=(page-1)*pageSize;
			List<User> userList=userDao.getAll();
			
			for(User m:userList) {
				if(m.getId()!=null) {
					m.setUsername(userDao.get(m.getId()).getUsername());
				}
			}
			//总记录数
			int totalRecords=userList.size();
			//总页数
			int totalPages=totalRecords % pageSize ==0 ? totalRecords / pageSize : totalRecords / pageSize +1;
			//某页结束的记录索引
			int endIndex=beginIndex+pageSize;  
			if(endIndex>totalRecords) {
				endIndex=totalRecords;
			}
			
			request.setAttribute("page", page);
			request.setAttribute("totalRecords", totalRecords);
			request.setAttribute("pageSize", pageSize);
			request.setAttribute("totalPages", totalPages);
			request.setAttribute("beginIndex", beginIndex);
			request.setAttribute("endIndex", endIndex);
			request.setAttribute("userList", userList);
			
			RequestDispatcher dispatcher=request.getRequestDispatcher("index.jsp");
			dispatcher.forward(request,response);
		}else if (type.equals("add")) {
			add(request, response, username, password);
		}else if(type.equals("get")) {
			get(request, response);
		}
	}

	private void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("id");
		User u=userDao.get(Integer.parseInt(id));
		request.setAttribute("user", u);
		RequestDispatcher dispatcher=request.getRequestDispatcher("admin/user/edituser.jsp");
		dispatcher.forward(request, response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response, String username, String password)
			throws IOException {
		int ret;
		User u=new User();
		u.setUsername(username);
		u.setPassword(password);
		ret=userDao.add(u);
		if(ret != 0) {
			response.sendRedirect(request.getContextPath()+"/user?type=getAll&page=1");
		}
	}

	private void reg(HttpServletRequest request, HttpServletResponse response, String username, String password)
			throws ServletException, IOException {
		int ret;
		if(StringUtils.isNotNullAndEmpty(username) && StringUtils.isNotNullAndEmpty(password)) {				
			if(userDao.isExist(username)) {
				//重名
				request.setAttribute("regInfo", "用户名已经使用，请更换！");
				RequestDispatcher dispatcher=request.getRequestDispatcher("/reg.jsp");
				dispatcher.forward(request, response);
			}else {
				//不重名
				User u=new User();
				u.setUsername(username);
				u.setPassword(password);
				u.setRoleId(2);
				ret=userDao.add(u);
				if(ret!=0) {					
					RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");
					dispatcher.forward(request, response);
				}else {
					request.setAttribute("regInfo", "注册失败！");
					RequestDispatcher dispatcher=request.getRequestDispatcher("/reg.jsp");
					dispatcher.forward(request, response);
				}
			}				
			
		}
	}

	private void login(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String username,
			String password) throws ServletException, IOException {
		
		HttpSession session = request.getSession();		
		User u;
		if(StringUtils.isNotNullAndEmpty(username) && StringUtils.isNotNullAndEmpty(password)) {//null
			u=userDao.login(username, password);
			if(u!=null) {
				System.out.println("u========="+u);
				session.setAttribute("loginInfo", u);
				response.sendRedirect(request.getContextPath()+"/index");
			}else {
				request.setAttribute("loginInfo", "用户名或密码错误！");
				RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");
				dispatcher.forward(request, response);
			}
		}else {
			out.println("用户名或者密码不能为空！");
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(requset, response);
	}
	

}
